#include "window/ImagesList.hpp"

ImagesList::ImagesList(CYFile* file, Editor* editor, QWidget* parent) : QDialog(parent){
    this->file = file;
    this->editor = editor;

    this->layout = new QVBoxLayout();

    this->nameLayout = new QHBoxLayout();
    this->nameLabel  = new QLabel(this->file->getFileName());

    this->scrollArea = new QScrollArea();
    this->imagesManager = new ImagesManager(this->scrollArea);

    this->buttonLayout = new QHBoxLayout();
    this->acceptButton = new QPushButton("确认");
    this->cancelButton = new QPushButton("取消");

    this->scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    this->scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    this->scrollArea->setWidget(this->imagesManager);

    this->nameLayout->addStretch();
    this->nameLayout->addWidget(this->nameLabel);
    this->nameLayout->addStretch();

    this->buttonLayout->addStretch();
    this->buttonLayout->addWidget(this->cancelButton);
    this->buttonLayout->addWidget(this->acceptButton);

    this->layout->addLayout(this->nameLayout);
    this->layout->addWidget(this->scrollArea);
    this->layout->addLayout(this->buttonLayout);

    this->setLayout(layout);

    // 设置窗口关闭后释放
    this->setAttribute(Qt::WA_DeleteOnClose);

    for(int i = 0; i < this->file->getImagesCount(); i++){
        this->imagesManager->images.push_back(this->file->getImage(i));

    }

    QObject::connect(this->cancelButton, SIGNAL(clicked()), this, SLOT(cancel()));
    QObject::connect(this->acceptButton, SIGNAL(clicked()), this, SLOT(accept()));

}

ImagesList::~ImagesList(){
    delete this->nameLabel;

    delete this->imagesManager;
    delete this->scrollArea;

    delete this->acceptButton;
    delete this->cancelButton;

    delete this->nameLayout;
    delete this->buttonLayout;
    
    delete this->layout;
    
}

void ImagesList::cancel(){
    this->close();

}

void ImagesList::accept(){
    for(int i = 0, count = this->file->getImagesCount(); i < count; i++){
        this->file->removeImage(0);

    }

    for(int i = 0; i < this->imagesManager->images.count(); i++){
        Image data = this->imagesManager->images.at(i);

        this->file->addImage(data.getImage());

        for(int j = 0; j < data.getNotesCount(); j++){
            this->file->addNote(i, data.getNote(j));

        }
        
    }

    this->file->saveFile();

    this->editor->reload();

    this->close();

}
